<?php

namespace App\Service\playlet;
use App\Model\Tag;
use App\Service\CommicService;
use Hyperf\Utils\ApplicationContext;
use App\Common\Response\SystemCode;
class TagService extends CommicService
{
    const cacheDuration = 60 * 15;
    public function __construct()
    {
        $container = ApplicationContext::getContainer();
        $this->redisService = $container->get(\Hyperf\Redis\Redis::class);
    }
    const STATUS_ENABLE  = 1;
    public function Search(Array $params){

        $keyword     = $params['keyword'] ?? '';

        $pageSize    = $params['pageSize'] ?? 10;
        $page        = $params['page'] ?? 1;

        $query = Tag::query()
            ->select(['id','name','sort','parent_id','created_at','updated_at']);

        if ($keyword) {
            $query->orWhere([['name', 'like', '%'.$keyword.'%']]);
        }
        $models = $query->orderBy('sort','asc')->orderBy('id','desc')->paginate($pageSize,['*'],'page',$page);
        return $models;
    }


    public function createOrUpdate(Array $postData, bool $is_update = false, Tag $TagInfo = null){

        $name = $postData['name'];
        $parent_id = $postData['parent_id'] ?? 0;
        $model = !empty($TagInfo)? $TagInfo : new Tag();
        $is_check_name = true;
        if($is_update) {
            //修改时判断集数是否一样
            if ($name == $model->name) {
                $is_check_name = false;
            }
        }
        if($is_check_name){
            $tagInfo = Tag::query()->where(['name' =>$name])->first();
            if(!empty($tagInfo)){
                return $this->response(SystemCode::SYSTEM_ERROR, '标签名称已存在');
            }

        }
        $model->parent_id = $parent_id;
        $model->name = $name;
        if($model->save()){
            return $this->response(SystemCode::SYSTEM_SUCCESS);
        }else{
            return $this->response(SystemCode::SYSTEM_ERROR,'保存错误');
        }
    }

}